import { ref, reactive, readonly, onMounted, onUnmounted } from 'vue'
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { invoke } from '@tauri-apps/api/core'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'

interface MenuEventPayload {
  action: string
  data?: any
}

interface AppMenuState {
  darkMode: boolean
  autoSave: boolean
  hasUnsavedChanges: boolean
  recentFiles: string[]
  viewMode: 'list' | 'grid' | 'card'
  notifications: boolean
  autoUpdate: boolean
}

interface AppSettings {
  language: string
  theme: string
  fontSize: number
}

export function useAppMenu() {
  const router = useRouter()

  // 菜单状态管理
  const menuState = reactive<AppMenuState>({
    darkMode: false,
    autoSave: true,
    hasUnsavedChanges: false,
    recentFiles: [],
    viewMode: 'card',
    notifications: true,
    autoUpdate: false
  })

  const appSettings = reactive<AppSettings>({
    language: 'zh-CN',
    theme: 'system',
    fontSize: 14
  })

  const isMenuReady = ref(false)
  let unlistenMenu: UnlistenFn | null = null

  // 菜单事件处理映射
  const menuHandlers: Record<string, (data?: any) => Promise<void> | void> = {
    // 文件菜单
    'file_new': handleNewProject,
    'file_open': handleOpenProject,
    'file_save': handleSaveProject,
    'file_save_as': handleSaveProjectAs,
    'file_export': handleExportProject,
    'file_import': handleImportData,
    'file_recent': handleRecentFile,
    'file_exit': handleExitApp,

    // 编辑菜单
    'edit_undo': handleUndo,
    'edit_redo': handleRedo,
    'edit_cut': handleCut,
    'edit_copy': handleCopy,
    'edit_paste': handlePaste,
    'edit_select_all': handleSelectAll,
    'edit_find': handleFind,
    'edit_preferences': handlePreferences,

    // 视图菜单
    'view_refresh': handleRefresh,
    'view_mode_list': () => handleViewMode('list'),
    'view_mode_grid': () => handleViewMode('grid'),
    'view_mode_card': () => handleViewMode('card'),
    'view_fullscreen': handleToggleFullscreen,
    'view_sidebar': handleToggleSidebar,
    'view_zoom_in': handleZoomIn,
    'view_zoom_out': handleZoomOut,
    'view_zoom_reset': handleZoomReset,

    // 工具菜单
    'tools_device_manager': () => { router.push('/devices').catch(console.error) },
    'tools_account_manager': () => { router.push('/accounts').catch(console.error) },
    'tools_task_center': () => { router.push('/tasks').catch(console.error) },
    'tools_content_library': () => { router.push('/content').catch(console.error) },
    'tools_analytics': () => { router.push('/analytics').catch(console.error) },
    'tools_settings': handleOpenSettings,
    'tools_logs': handleOpenLogs,

    // 窗口菜单
    'window_minimize': handleMinimizeWindow,
    'window_maximize': handleMaximizeWindow,
    'window_close': handleCloseWindow,
    'window_new': handleNewWindow,

    // 帮助菜单
    'help_documentation': handleOpenDocumentation,
    'help_keyboard_shortcuts': handleShowShortcuts,
    'help_check_updates': handleCheckUpdates,
    'help_feedback': handleSendFeedback,
    'help_about': handleShowAbout,

    // 切换选项
    'toggle_dark_mode': handleToggleDarkMode,
    'toggle_auto_save': handleToggleAutoSave,
    'toggle_notifications': handleToggleNotifications,
    'toggle_auto_update': handleToggleAutoUpdate
  }

  // 主菜单事件处理器
  const handleMenuEvent = async(payload: MenuEventPayload) => {
    console.log('📋 Menu event received:', payload)

    const handler = menuHandlers[payload.action]
    if (handler) {
      try {
        await handler(payload.data)
      } catch (error) {
        console.error(`❌ Menu handler failed for ${payload.action}:`, error)
        ElMessage.error(`菜单操作失败: ${payload.action}`)
      }
    } else {
      console.warn('⚠️ Unknown menu action:', payload.action)
    }
  }

  // === 文件菜单处理函数 ===
  async function handleNewProject() {
    if (menuState.hasUnsavedChanges) {
      const shouldSave = await confirmSaveChanges()
      if (shouldSave === null) return // 用户取消
      if (shouldSave) await handleSaveProject()
    }

    ElMessage.success('创建新项目')
    menuState.hasUnsavedChanges = false
    await updateMenuState()
  }

  async function handleOpenProject() {
    try {
      const result = await invoke('show_open_dialog', {
        filters: [{
          name: 'SocialMatrix 项目',
          extensions: ['smp']
        }]
      })
      
      if (result) {
        ElMessage.success(`打开项目: ${result}`)
        menuState.recentFiles.unshift(result as string)
        await updateRecentFiles()
      }
    } catch (error) {
      ElMessage.error('打开项目失败')
    }
  }

  async function handleSaveProject() {
    try {
      await invoke('save_current_project')
      ElMessage.success('项目已保存')
      menuState.hasUnsavedChanges = false
      await updateMenuState()
    } catch (error) {
      ElMessage.error('保存项目失败')
    }
  }

  async function handleSaveProjectAs() {
    try {
      const result = await invoke('show_save_dialog', {
        defaultPath: 'project.smp',
        filters: [{
          name: 'SocialMatrix 项目',
          extensions: ['smp']
        }]
      })

      if (result) {
        await invoke('save_project_as', { path: result })
        ElMessage.success(`项目已保存为: ${result}`)
        menuState.hasUnsavedChanges = false
        await updateMenuState()
      }
    } catch (error) {
      ElMessage.error('另存为失败')
    }
  }

  async function handleExportProject() {
    ElNotification({
      title: '导出功能',
      message: '项目导出功能正在开发中...',
      type: 'info'
    })
  }

  async function handleImportData() {
    router.push('/accounts/import')
  }

  async function handleRecentFile(data: any) {
    const filePath = data?.path
    if (filePath) {
      try {
        await invoke('open_recent_file', { path: filePath })
        ElMessage.success(`打开最近文件: ${filePath}`)
      } catch (error) {
        ElMessage.error('打开最近文件失败')
      }
    }
  }

  async function handleExitApp() {
    if (menuState.hasUnsavedChanges) {
      const shouldSave = await confirmSaveChanges()
      if (shouldSave === null) return
      if (shouldSave) await handleSaveProject()
    }
    
    await invoke('exit_app')
  }

  // === 编辑菜单处理函数 ===
  async function handleUndo() {
    await invoke('editor_undo')
    ElMessage.info('撤销操作')
  }

  async function handleRedo() {
    await invoke('editor_redo')
    ElMessage.info('重做操作')
  }

  async function handleCut() {
    await invoke('editor_cut')
    ElMessage.info('剪切')
  }

  async function handleCopy() {
    await invoke('editor_copy')
    ElMessage.info('复制')
  }

  async function handlePaste() {
    await invoke('editor_paste')
    ElMessage.info('粘贴')
    markDocumentChanged()
  }

  async function handleSelectAll() {
    await invoke('editor_select_all')
    ElMessage.info('全选')
  }

  async function handleFind() {
    // 触发搜索功能
    const searchEvent = new CustomEvent('app-search', { detail: { focus: true } })
    document.dispatchEvent(searchEvent)
  }

  async function handlePreferences() {
    router.push('/settings')
  }

  // === 视图菜单处理函数 ===
  async function handleRefresh() {
    // 使用更安全的刷新方式，避免无限循环
    console.log('🔄 手动刷新页面')
    ElMessage.info('页面刷新中...')
    // 延迟刷新避免与HMR冲突
    setTimeout(() => {
      window.location.reload()
    }, 100)
  }

  async function handleViewMode(mode: 'list' | 'grid' | 'card') {
    menuState.viewMode = mode
    ElMessage.success(`切换到${mode}视图`)
    await invoke('set_view_mode', { mode })
  }

  async function handleToggleFullscreen() {
    await invoke('toggle_fullscreen')
  }

  async function handleToggleSidebar() {
    const sidebarEvent = new CustomEvent('app-sidebar-toggle')
    document.dispatchEvent(sidebarEvent)
  }

  async function handleZoomIn() {
    appSettings.fontSize = Math.min(appSettings.fontSize + 2, 24)
    document.documentElement.style.fontSize = `${appSettings.fontSize}px`
    ElMessage.info(`字体大小: ${appSettings.fontSize}px`)
  }

  async function handleZoomOut() {
    appSettings.fontSize = Math.max(appSettings.fontSize - 2, 10)
    document.documentElement.style.fontSize = `${appSettings.fontSize}px`
    ElMessage.info(`字体大小: ${appSettings.fontSize}px`)
  }

  async function handleZoomReset() {
    appSettings.fontSize = 14
    document.documentElement.style.fontSize = '14px'
    ElMessage.info('重置字体大小')
  }

  // === 工具菜单处理函数 ===
  async function handleOpenSettings() {
    router.push('/settings')
  }

  async function handleOpenLogs() {
    try {
      await invoke('open_logs_folder')
    } catch (error) {
      ElMessage.error('打开日志文件夹失败')
    }
  }

  // === 窗口菜单处理函数 ===
  async function handleMinimizeWindow() {
    await invoke('minimize_window')
  }

  async function handleMaximizeWindow() {
    await invoke('toggle_maximize')
  }

  async function handleCloseWindow() {
    await handleExitApp()
  }

  async function handleNewWindow() {
    await invoke('create_new_window')
  }

  // === 帮助菜单处理函数 ===
  async function handleOpenDocumentation() {
    await invoke('open_url', { url: 'https://docs.socialmatrix.pro' })
  }

  async function handleShowShortcuts() {
    ElMessageBox.alert(`
      <div style="text-align: left;">
        <h3>常用快捷键</h3>
        <p><kbd>Ctrl+N</kbd> - 新建项目</p>
        <p><kbd>Ctrl+O</kbd> - 打开项目</p>
        <p><kbd>Ctrl+S</kbd> - 保存项目</p>
        <p><kbd>Ctrl+Z</kbd> - 撤销</p>
        <p><kbd>Ctrl+Y</kbd> - 重做</p>
        <p><kbd>Ctrl+F</kbd> - 查找</p>
        <p><kbd>Ctrl+K</kbd> - 菜单搜索</p>
        <p><kbd>F11</kbd> - 全屏模式</p>
        <p><kbd>Ctrl+,</kbd> - 设置</p>
      </div>
    `, '快捷键指南', {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true
    })
  }

  async function handleCheckUpdates() {
    try {
      const result = await invoke('check_for_updates')
      if (result) {
        ElNotification({
          title: '发现新版本',
          message: '有新版本可用，正在下载更新...',
          type: 'success'
        })
      } else {
        ElMessage.success('当前已是最新版本')
      }
    } catch (error) {
      ElMessage.error('检查更新失败')
    }
  }

  async function handleSendFeedback() {
    await invoke('open_url', { url: 'https://feedback.socialmatrix.pro' })
  }

  async function handleShowAbout() {
    try {
      const version = await invoke('get_app_version')
      ElMessageBox.alert(`
        <div style="text-align: center;">
          <h2>SocialMatrix Pro</h2>
          <p>版本: ${version}</p>
          <p>专业的海外社媒矩阵管理平台</p>
          <p>构建于 Tauri 2.0 + Vue 3 + Rust</p>
          <br>
          <p><small>© 2024 SocialMatrix Pro Team</small></p>
        </div>
      `, '关于应用', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    } catch (error) {
      ElMessage.error('获取版本信息失败')
    }
  }

  // === 切换选项处理函数 ===
  async function handleToggleDarkMode(data?: any) {
    const enabled = data?.enabled ?? !menuState.darkMode
    menuState.darkMode = enabled
    
    // 应用主题
    document.documentElement.classList.toggle('dark', enabled)
    document.documentElement.setAttribute('data-theme', enabled ? 'dark' : 'light')
    
    ElMessage.success(`${enabled ? '启用' : '禁用'}深色模式`)
    
    // 保存设置
    appSettings.theme = enabled ? 'dark' : 'light'
    await saveAppSettings()
  }

  async function handleToggleAutoSave(data?: any) {
    const enabled = data?.enabled ?? !menuState.autoSave
    menuState.autoSave = enabled
    ElMessage.success(`${enabled ? '启用' : '禁用'}自动保存`)
    await saveAppSettings()
  }

  async function handleToggleNotifications(data?: any) {
    const enabled = data?.enabled ?? !menuState.notifications
    menuState.notifications = enabled
    ElMessage.success(`${enabled ? '启用' : '禁用'}桌面通知`)
    await saveAppSettings()
  }

  async function handleToggleAutoUpdate(data?: any) {
    const enabled = data?.enabled ?? !menuState.autoUpdate
    menuState.autoUpdate = enabled
    ElMessage.success(`${enabled ? '启用' : '禁用'}自动更新`)
    await saveAppSettings()
  }

  // === 辅助函数 ===
  async function confirmSaveChanges(): Promise<boolean | null> {
    try {
      await ElMessageBox.confirm(
        '当前项目有未保存的更改，是否保存？',
        '确认保存',
        {
          confirmButtonText: '保存',
          cancelButtonText: '不保存',
          distinguishCancelAndClose: true,
          type: 'warning'
        }
      )
      return true // 用户选择保存
    } catch (action) {
      if (action === 'cancel') {
        return false // 用户选择不保存
      }
      return null // 用户取消操作
    }
  }

  // 标记文档已更改
  const markDocumentChanged = async() => {
    if (!menuState.hasUnsavedChanges) {
      menuState.hasUnsavedChanges = true
      await updateMenuState()
    }
  }

  // 标记文档已保存
  const markDocumentSaved = async() => {
    if (menuState.hasUnsavedChanges) {
      menuState.hasUnsavedChanges = false
      await updateMenuState()
    }
  }

  // 更新菜单状态 (本地状态管理，不再调用后端)
  const updateMenuState = async() => {
    // 菜单状态现在仅在前端管理
    // 可以在这里添加本地存储逻辑
    localStorage.setItem('menuState', JSON.stringify({
      hasUnsavedChanges: menuState.hasUnsavedChanges,
      darkMode: menuState.darkMode,
      autoSave: menuState.autoSave,
      viewMode: menuState.viewMode
    }))
  }

  // 更新最近文件列表
  const updateRecentFiles = async() => {
    try {
      await invoke('update_recent_files', { files: menuState.recentFiles })
    } catch (error) {
      console.error('Failed to update recent files:', error)
    }
  }

  // 保存应用设置
  const saveAppSettings = async() => {
    try {
      await invoke('save_app_settings', { settings: appSettings })
      localStorage.setItem('appSettings', JSON.stringify(appSettings))
    } catch (error) {
      console.error('Failed to save app settings:', error)
    }
  }

  // 加载应用设置
  const loadAppSettings = async() => {
    try {
      const saved = localStorage.getItem('appSettings')
      if (saved) {
        Object.assign(appSettings, JSON.parse(saved))
      }
      
      // 从后端加载设置
      const backendSettings = await invoke('load_app_settings')
      if (backendSettings) {
        Object.assign(appSettings, backendSettings)
      }
    } catch (error) {
      console.error('Failed to load app settings:', error)
    }
  }

  // 初始化菜单系统
  const initializeMenu = async() => {
    try {
      await loadAppSettings()
      
      // 从本地存储加载菜单状态
      const savedMenuState = localStorage.getItem('menuState')
      if (savedMenuState) {
        try {
          const parsed = JSON.parse(savedMenuState)
          Object.assign(menuState, parsed)
        } catch (e) {
          console.warn('Failed to parse saved menu state:', e)
        }
      }
      
      // 应用保存的主题
      if (appSettings.theme === 'dark' || 
          (appSettings.theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        menuState.darkMode = true
        document.documentElement.classList.add('dark')
        document.documentElement.setAttribute('data-theme', 'dark')
      }

      // 应用字体大小
      if (appSettings.fontSize) {
        document.documentElement.style.fontSize = `${appSettings.fontSize}px`
      }

      isMenuReady.value = true
    } catch (error) {
      console.error('Failed to initialize menu:', error)
    }
  }

  // 生命周期管理
  onMounted(async() => {
    try {
      // 设置菜单事件监听器
      unlistenMenu = await listen<MenuEventPayload>('menu-event', (event) => {
        handleMenuEvent(event.payload)
      })

      await initializeMenu()
    } catch (error) {
      console.error('Failed to setup menu system:', error)
    }
  })

  onUnmounted(() => {
    if (unlistenMenu) {
      unlistenMenu()
    }
  })

  return {
    // 状态
    menuState: readonly(menuState),
    appSettings: readonly(appSettings),
    isMenuReady: readonly(isMenuReady),

    // 方法
    markDocumentChanged,
    markDocumentSaved,
    updateMenuState,
    saveAppSettings,
    loadAppSettings,

    // 直接调用的菜单操作
    newProject: handleNewProject,
    openProject: handleOpenProject,
    saveProject: handleSaveProject,
    toggleDarkMode: handleToggleDarkMode,
    toggleAutoSave: handleToggleAutoSave,
    showAbout: handleShowAbout,
    showShortcuts: handleShowShortcuts
  }
}